//
//  NKListeningController.m
//  NiKi
//
//  Created by qiang chen on 16/6/12.
//  Copyright © 2016年 qiang chen. All rights reserved.
//

#import "NKListeningController.h"
#import <AFSoundManager.h>
#import "NKPlayingCell.h"
#import "NSString+OXExtension.h"

@interface NKListeningController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,NKPlayingCellDelegate>{
    __weak IBOutlet UILabel *_allTimeLb;
    __weak IBOutlet UILabel *_currentTimeLb;
    __weak IBOutlet UICollectionView *_playCollectionV;
    __weak IBOutlet UISlider *_progress;
    __weak IBOutlet NSLayoutConstraint *_collectionVH;
    AFSoundItem *_currentPlayItem;
    NSArray *_playItems;//播放item的数组
}

/**
 *  在xib中创建listenHandle设置anchorPoint真操蛋
 */
@property (nonatomic, strong) UIImageView *listenHandleV;
@property (nonatomic, strong) AFSoundPlayback *playManager;//播放列表
@end

@implementation NKListeningController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
     self.playManager = nil;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    _playItems = @[
                   [self creatItemWithStr:@"http://sc1.111ttt.com/2016/5/06/22/199221401504.mp3"],
                   [self creatItemWithStr:@"http://sc1.111ttt.com/2016/1/06/22/199220947369.mp3"]
                   ];
    [self playMusicWithIndex:0];
}

- (AFSoundItem *)creatItemWithStr:(NSString *)str {
    NSURL *url = [NSURL URLWithString:str];
    AFSoundItem *item = [[AFSoundItem alloc]initWithStreamingURL:url];
    return item;
}

#pragma mark - 设置UI
/**
 *  初始化UI
 */
- (void)setupUI {
    self.view.layer.contents = (id)[UIImage imageNamed:@"背景底图"].CGImage;
    self.view.layer.contentsGravity = kCAGravityResizeAspectFill;
    
    [_progress setThumbImage:[UIImage imageNamed:@"listen_progress-bar-btn"] forState:UIControlStateNormal];
    
    _collectionVH.constant = 270/667.f*ScreenH;
    [_playCollectionV registerNib:[UINib nibWithNibName:NSStringFromClass([NKPlayingCell class]) bundle:nil] forCellWithReuseIdentifier:playingCell];
    
    [self.view addSubview:self.listenHandleV];
   
}

- (UIImageView *)listenHandleV {
    if (!_listenHandleV) {
        _listenHandleV = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenW - 110)*0.5, 0, 110, 80)];
        _listenHandleV.backgroundColor = [UIColor clearColor];
        _listenHandleV.image = [UIImage imageNamed:@"listen_needle"];
        _listenHandleV.layer.anchorPoint = CGPointMake(0.5, 0);
        _listenHandleV.layer.position = CGPointMake(ScreenW*0.5, 0);
    }
    return _listenHandleV;
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

//播放
- (void)playMusicWithIndex:(NSInteger)index {
    [self.playManager pause];
    _currentPlayItem = _playItems[index];
    self.playManager = [[AFSoundPlayback alloc]initWithItem:_currentPlayItem];
    //播放回调
    [self.playManager listenFeedbackUpdatesWithBlock:^(AFSoundItem *item) {
        NSInteger index = [_playItems indexOfObject:item];
        NKPlayingCell *cell = (NKPlayingCell *)[_playCollectionV cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
        cell.progress = (CGFloat)item.timePlayed/item.duration;
        
        //更新滑块
        _progress.value = (CGFloat)item.timePlayed/item.duration;
        
        //更新标签
        _currentTimeLb.text = [NSString stringWithTime:item.timePlayed];
        _allTimeLb.text = [NSString stringWithTime:item.duration];
        
        NSLog(@"当前播放时间 = %zd，总时长 = %zd",item.timePlayed,item.duration);
    } andFinishedBlock:^{
        
    }];
    
    [self startListenHandleAnimateWithToValue:@(0)];
}

#pragma mark - 滑块事件
//点击
- (IBAction)progressClick:(UITapGestureRecognizer *)sender {
    CGPoint point = [sender locationInView:sender.view];
    CGFloat ratio = point.x/_progress.width;
    [self.playManager playAtSecond:ratio*_currentPlayItem.duration];
}

- (IBAction)progressValueChange:(UISlider *)sender {
}

- (IBAction)progressClickStart:(UISlider *)sender {
}

- (IBAction)progressClickEnd:(UISlider *)sender {
     [self.playManager playAtSecond:sender.value*_currentPlayItem.duration];
}


#pragma mark - UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 2;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NKPlayingCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:playingCell forIndexPath:indexPath];
    cell.delegate = self;
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(ScreenW,collectionView.height);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == _playCollectionV) {
        NSInteger index = scrollView.contentOffset.x/CGRectGetWidth(scrollView.frame);
        NSInteger playIndex = [_playItems indexOfObject:_currentPlayItem];
        if (index == playIndex) {
            
        }else{
            [self playMusicWithIndex:index];
        }
    }
}

#pragma mark - NKPlayingCellDelegate
- (void)NKPlayingCell:(NKPlayingCell *)cell playStatusBtnClick:(UIButton *)btn {
    if (btn.isSelected) {
        [self.playManager play];
        [self startListenHandleAnimateWithToValue:@(0)];
    }else {
        [self.playManager pause];
        [_listenHandleV.layer removeAllAnimations];
    }
    btn.selected = !btn.selected;
}

#pragma mark - ListenHandleAnimate 
- (void)startListenHandleAnimateWithToValue:(NSNumber *)toValue {
    CABasicAnimation *anim = [CABasicAnimation animation];
    anim.keyPath = @"transform.rotation.z";
    anim.toValue = toValue;
    anim.repeatCount = 1;
    anim.duration = 1;
    anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    anim.removedOnCompletion = NO;
    anim.fillMode = kCAFillModeForwards;
    [_listenHandleV.layer addAnimation:anim forKey:nil];
}

#pragma mark - 添加远程事件
- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    /*
     UIEventSubtypeRemoteControlPlay                 = 100,
     UIEventSubtypeRemoteControlPause                = 101,
     UIEventSubtypeRemoteControlStop                 = 102,
     UIEventSubtypeRemoteControlTogglePlayPause      = 103,
     UIEventSubtypeRemoteControlNextTrack            = 104,
     UIEventSubtypeRemoteControlPreviousTrack        = 105,
     UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
     UIEventSubtypeRemoteControlEndSeekingBackward   = 107,
     UIEventSubtypeRemoteControlBeginSeekingForward  = 108,
     UIEventSubtypeRemoteControlEndSeekingForward    = 109,
     */
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
        case UIEventSubtypeRemoteControlPause:{
            NSInteger index = [_playItems indexOfObject:_currentPlayItem];
            NKPlayingCell *cell = (NKPlayingCell *)[_playCollectionV cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
            [self NKPlayingCell:cell playStatusBtnClick:cell.statusBtn];
        }
            break;
        case UIEventSubtypeRemoteControlNextTrack:

            break;
            
        case UIEventSubtypeRemoteControlPreviousTrack:

            break;
            
        default:
            break;
    }
}

@end
